﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using CSRedis;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base
{
    public partial class Base_UnitGroupBusiness : BaseBusiness<Base_UnitGroup>, IBase_UnitGroupBusiness, ITransientDependency
    {
        private static CSRedisClient RediC;

        public Base_UnitGroupBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<Base_UnitGroup>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_UnitGroup>();
            var search = input.Search;
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.Name, keyword)
                      || EF.Functions.Like(x.Code, keyword));
            }
            return await q.GetPageResultAsync(input);
        }

        public async Task<PageResult<Base_UnitGroup>> GetDataListAsyncs(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_UnitGroup>();
            var search = input.Search;

            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_UnitGroup, bool>(
                    ParsingConfig.Default, false, $@"Code.Contains(@0) or Name.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_UnitGroup> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.计量单位, "Name", "计量单位组")]
        [DataRepeatValidate(new string[] { "Code" }, new string[] { "计量单位组编码" })]
        public async Task AddDataAsync(Base_UnitGroup data, RedisOptions _redisOptions)
        {
            Dictionary<string, string> TagSet;
            _redisOptions.DbChannel = (int)Redis_Type.redis8;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            RedisSetHelper.KeyDelete("BaseUnitGroupRedis");
            if (data.IsDefault)
            {
                await ExecuteSqlAsync("update Base_UnitGroup  SET IsDefault=0 where Id!='" + data.Id + "'");
            }
            await InsertAsync(data);
            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                var rs = RediC.HGetAll("BaseUnitGroupRedis");
                if (rs == null && rs.Keys.Count() == 0)
                {
                    var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                    TagSet = new Dictionary<string, string>();
                    foreach (var item in UnitGroup)
                    {
                        TagSet.Add(item.Id, item.Name);//
                    }
                    RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
                }
            }
            else
            {
                var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                TagSet = new Dictionary<string, string>();
                foreach (var item in UnitGroup)
                {
                    TagSet.Add(item.Id, item.Name);//
                }
                RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
            }
        }

        [DataEditLog(UserLogType.计量单位, "Name", "计量单位组")]
        [DataRepeatValidate(new string[] { "Code" }, new string[] { "计量单位组编码" })]
        public async Task UpdateDataAsync(Base_UnitGroup data, RedisOptions _redisOptions)
        {
            _redisOptions.DbChannel = (int)Redis_Type.redis8;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            RedisSetHelper.KeyDelete("BaseUnitGroupRedis");
            //判断当前数据状态是true
            if (data.IsDefault)
            {
                //批量修改分组下所有数据记录的状态为false
                await ExecuteSqlAsync("update Base_UnitGroup SET IsDefault=0 where  Id!='" + data.Id + "'");
            }
            await UpdateAsync(data);
            Dictionary<string, string> TagSet;

            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                var rs = RediC.HGetAll("BaseUnitGroupRedis");
                if (rs == null && rs.Keys.Count() == 0)
                {
                    var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                    TagSet = new Dictionary<string, string>();
                    foreach (var item in UnitGroup)
                    {
                        TagSet.Add(item.Id, item.Name);//
                    }
                    RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
                }
            }
            else
            {
                var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                TagSet = new Dictionary<string, string>();
                foreach (var item in UnitGroup)
                {
                    TagSet.Add(item.Id, item.Name);//
                }
                RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);

            }
        }

        [DataDeleteLog(UserLogType.计量单位, "Name", "计量单位")]
        public async Task DeleteDataAsync(List<string> ids)
        {

            if (await Db.GetIQueryable<Base_UnitItems>().AnyAsync(x => ids.Contains(x.GroupId)))
            {
                throw new BusException("删除失败！该单位组下有子单位,请先删除子单位！");
            }
            new RedisOptions().DbChannel = 8;
            RedisSetHelper redis = new RedisSetHelper(new RedisOptions());
            RedisSetHelper.KeyDelete("BaseUnitGroupRedis");
            await DeleteAsync(ids);
            Dictionary<string, string> TagSet;
            if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
            {
                var rs = RediC.HGetAll("BaseUnitGroupRedis");
                if (rs == null && rs.Keys.Count() == 0)
                {
                    var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                    TagSet = new Dictionary<string, string>();
                    foreach (var item in UnitGroup)
                    {
                        TagSet.Add(item.Id, item.Name);//
                    }
                    RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);
                }
            }
            else
            {
                var UnitGroup = Db.GetListBySql<Base_UnitGroup>("SELECT CONCAT_WS('_',GroupId,Name) as Id,Id as `Name`   from  Base_UnitItems where`Deleted`=FALSE");
                TagSet = new Dictionary<string, string>();
                foreach (var item in UnitGroup)
                {
                    TagSet.Add(item.Id, item.Name);//
                }
                RedisSetHelper.SetHash("BaseUnitGroupRedis", TagSet);

            }
        }

        #endregion

        #region 私有成员

        #endregion
    }
}